package com.welab.pandahelper.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.Gson;
import com.welab.pandahelper.R;
import com.welab.pandahelper.bean.CustomDialog;
import com.welab.pandahelper.bean.MyResponse;
import com.welab.pandahelper.bean.PandaGift;
import com.welab.pandahelper.config.MyConfig;
import com.welab.pandahelper.http.OkHttpHelper;
import com.welab.pandahelper.http.SpotsCallBack;
import com.welab.pandahelper.utils.codeUtils;
import com.welab.pandahelper.utils.taskUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

import static com.welab.pandahelper.utils.codeUtils.getToken;
import static com.welab.pandahelper.utils.codeUtils.pandaSendCode;
import static com.welab.pandahelper.utils.codeUtils.sendCode;
import static com.welab.pandahelper.utils.codeUtils.setCodeType;
import static com.welab.pandahelper.utils.codeUtils.setPhone;

public class HelperActivity extends AppCompatActivity implements TextWatcher {


    private static SharedPreferences mPrefs;
    private Button send_code_btn;
    private EditText phone_text;
    private EditText code_text;
    private Button check_code_btn;
    private static Boolean startFlag;
    private static Boolean exitFlag;
    private Button check_token;
    private com.welab.pandahelper.utils.codeUtils codeUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_helper);
        startFlag = false;
        exitFlag = false;
        check_token = (Button)findViewById(R.id.check_token);
        send_code_btn = (Button) findViewById(R.id.send_code);
        phone_text = (EditText) findViewById(R.id.edit_phone);
        phone_text.addTextChangedListener(this);
        code_text = (EditText) findViewById(R.id.edit_code);
        check_code_btn = (Button) findViewById(R.id.check_code);
        mPrefs = getApplicationContext().getSharedPreferences("panda_token", Context.MODE_PRIVATE);
        final MyCountDownTimer myCountDownTimer = new MyCountDownTimer(60000,1000);
        final MyCountDownTimer getTokenDownTimer = new MyCountDownTimer(10000,1000);
        send_code_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String phone = phone_text.getText().toString();
                if (phone.equals("") || phone.length() != 11) {
                    Toast.makeText(HelperActivity.this, "请输入正确的手机号！", Toast.LENGTH_SHORT).show();
                } else {
                    String token = mPrefs.getString(phone,"0");
                    if ("0".equals(token)){
                        try {
                            codeUtils.setCodeType("panda");
                            codeUtils.setPhone(phone);
                            codeUtils.sendCode(HelperActivity.this);
                            send_code_btn.setClickable(false);
                            myCountDownTimer.setButton(send_code_btn);
                            myCountDownTimer.start();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }else {
                        Toast.makeText(HelperActivity.this, "无需获取手机验证码，可直接开始！", Toast.LENGTH_SHORT).show();
                    }
                }

            }
        });


        check_token.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = phone_text.getText().toString();
                String token = mPrefs.getString(phone,"0");
                if ("0".equals(token)){
                    String code = code_text.getText().toString();
                    if (!code.equals("")){
                        codeUtils.setCodeType("panda");
                        codeUtils.getToken(HelperActivity.this,code,phone);
                    }
                }else {
                    Toast.makeText(HelperActivity.this,"无需认证，可直接开始抢单！",Toast.LENGTH_LONG).show();
                }
            }
        });

        check_code_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = phone_text.getText().toString();
                String token = mPrefs.getString(phone,"0");
                if ("0".equals(token)){
                    Toast.makeText(HelperActivity.this,"当前号码认证信息不正确，请获取验证码后进行认证！！",Toast.LENGTH_LONG).show();
                }else {
                    check_code_btn.setText("xxxx");
                    check_code_btn.setClickable(false);
                    startFlag = true;
                    getPandaTask(HelperActivity.this,token);
                }
            }
        });
    }

//    private void clearTimer() {
//        if (task != null) {
//            task.cancel();
//            task = null;
//        }
//        if (timer != null) {
//            timer.cancel();
//            timer = null;
//        }
//    }

    public void onPickAppClick(View v) {
//        NiceDialog.init()
//                .setLayoutId(R.layout.dialog_apps_list)
//                .setConvertListener(new ViewConvertListener() {
//                    @Override
//                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
//                        holder.getView(R.id.confirm_btn).setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//
//                                dialog.dismiss();
//                            }
//                        });
//                        holder.getView(R.id.cancel_btn).setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                dialog.dismiss();
//                            }
//                        });
//                        ListView lv = holder.getView(R.id.apps_lv);
//
//
//                        lv.setAdapter(new AppsListAdapter(dialog.getContext(), mApps));
//                        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                            @Override
//                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                                ExpandableListItem item = (ExpandableListItem) parent.getAdapter().getItem(position);
//                                if (item != null) {
//                                    txtAppSelected.setText(item.getAppName());
//                                    checkedApp(position);
//                                    task.setApp_name(item.getAppName());
//                                    task.setPackage_name(item.getPckName());
//                                }
//                                dialog.dismiss();
//                            }
//                        });
//                    }
//                })
//                .setGravity(Gravity.BOTTOM)
//                .setHeight(520)
//                .show(getSupportFragmentManager());
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    private class MyCountDownTimer extends CountDownTimer {

        private Button button;

        public Button getButton() {
            return button;
        }

        public void setButton(Button button) {
            this.button = button;
        }

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }
        //计时过程
        @Override
        public void onTick(long l) {
            //防止计时过程中重复点击
            button.setText(l/1000+"秒");

        }

        //计时完毕的方法
        @Override
        public void onFinish() {
            //重新给Button设置文字
            button.setText("重新获取");
            //设置可点击
            button.setClickable(true);
        }
    }

    public void getPandaTask(Context context,String token){

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (startFlag){
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    try {
                        MyResponse myResponse = taskUtils.getPandaTaskList(token);
//                        Log.e(MyConfig.APP_NAME,myResponse.getMsg());
                        List<Map<String,Object>> giftList = (List<Map<String,Object>>)myResponse.getData();
//                        Log.e(MyConfig.APP_NAME,giftList.size()+"");
                        if (giftList != null && giftList.size() > 0){
                            for (Map<String,Object> gift:giftList
                            ) {
//                                String url = String.valueOf(Double.valueOf(gift.get("giftLevel")).intValue());
                                String url = gift.get("giftLevel") + "";
                                Log.e(MyConfig.APP_NAME,url);
                                PandaGift pandaGift = new PandaGift(gift);
                                if (pandaGift!=null){
                                    if(taskUtils.getPandaTask(HelperActivity.this,pandaGift,token)){
                                        startFlag = false;
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();


        check_code_btn.setText("抢单中,请勿离开此页面，最好别动---");
        check_code_btn.post(new Runnable() {
            @Override
            public void run() {


            }
        });


        Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                CustomDialog mDialog=new CustomDialog(HelperActivity.this, "温馨提示", "抢单成功！！?", "确定",new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                mDialog.dismiss();
                        Toast.makeText(HelperActivity.this,"抢到单了--开心赚钱",Toast.LENGTH_LONG).show();
                        Intent i = new Intent(HelperActivity.this,MainActivity.class);
                        startActivity(i);
                        finish();
                    }
                });
                mDialog.setCanotBackPress();
                mDialog.setCanceledOnTouchOutside(false);
                mDialog.show();
            }
        };

        new Thread(){
            @Override
            public void run() {
                try {
                    while (startFlag){
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if(!exitFlag){
                        Message message = new Message();
                        message.obj = true;
                        handler.sendMessage(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
        Toast.makeText(HelperActivity.this,"抢单成功后会弹窗提示！！！",Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onDestroy() {
        //将线程销毁掉
        super.onDestroy();
        startFlag = false;
        exitFlag = true;
    }
}

